<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-10-13
 * Time: 上午8:35
 */

namespace App\Controllers\Admin;

use \App\Controllers\Application;

class Setting extends Application {

	public function __construct(...$params) {
		parent::__construct(...$params);
		if (!$this->user) {
			$this->showError("用户尚未登录，请登录后重新打开。", site_url('/user/'));
		}
	}

	public function index() {
		$this->data['settings'] = $this->setting->findAll();
		$this->render('admin/setting/list', '系统设置');
	}

	public function add($id = '') {
		if ($id) {
			$this->data['setting'] = $this->setting->find($id);
		}

		$this->render('admin/setting/add');
	}

	public function save() {
		$pk = $this->request->getPost('pk');
		if ($pk) {
			$setting[$this->request->getPost('name')] = $this->request->getPost('value');
			$this->setting->update($pk, $setting);
		} else {
		    $option=$this->request->getPost('options')?json_encode(explode(",",$this->request->getPost('options'))):'';

			$setting = [
				'id' => $this->request->getPost('id'),
				'name' => $this->request->getPost('name'),
				'desc' => $this->request->getPost('desc'),
				'value' => $this->request->getPost('value'),
				'type' => $this->request->getPost('type'),
				'options' => $option,
			];

			$this->setting->save($setting);
			$pk = $this->db->insertID();
		}
		$this->showJson(['message' => '保存设置成功', 'pk' => $pk]);
	}

}